import requests
import json
import csv

def fetch_nba_rankings():
    """
    从新浪体育网站获取2023-2024赛季NBA常规赛排名数据
    
    返回:
    tuple: (东部球队列表, 西部球队列表)
    """
    # API URL（通过浏览器开发者工具获取）
    url = "https://slamdunk.sports.sina.com.cn/api/public/rank"
    
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
    }

    try:
        response = requests.get(url, headers=headers)
        
        if response.status_code == 200:
            data = response.json()
            
            # 提取东部和西部球队数据
            east_teams = data.get('data', {}).get('east', [])
            west_teams = data.get('data', {}).get('west', [])
            
            return east_teams, west_teams
        else:
            print(f"请求失败，状态码：{response.status_code}")
            return None, None
            
    except requests.exceptions.RequestException as e:
        print(f"网络请求异常: {e}")
        return None, None
    except json.JSONDecodeError as e:
        print(f"JSON解析错误: {e}")
        return None, None

def save_as_json(east_teams, west_teams, filename='nba_rankings_2023_2024.json'):
    """将球队数据保存为JSON格式"""
    data = {
        'east': east_teams,
        'west': west_teams
    }
    
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=4)
    print(f"✅ 数据已成功保存到 JSON 文件: {filename}")

def save_as_csv(east_teams, west_teams, filename='nba_rankings_2023_2024.csv'):
    """将球队数据保存为CSV格式"""
    # 获取所有可能的字段名
    all_fields = set()
    for team in east_teams + west_teams:
        all_fields.update(team.keys())
    
    # 排除不需要显示的字段
    excluded_fields = {'id', 'groupId', 'conference'}
    fieldnames = sorted([field for field in all_fields if field not in excluded_fields])
    
    # 字段名称映射（中文标题）
    field_mapping = {
        'name': '球队名称',
        'rank': '排名',
        'win': '胜场',
        'lose': '负场',
        'rate': '胜率',
        'gamesBehind': '落后场次',
        'home': '主场战绩',
        'away': '客场战绩',
        'recentGame': '近期战绩',
        'point': '积分'
    }
    
    with open(filename, 'w', newline='', encoding='utf-8-sig') as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        
        # 写入表头
        writer.writerow({field: field_mapping.get(field, field) for field in fieldnames})
        
        # 写入数据
        for team in east_teams + west_teams:
            filtered_team = {field: team.get(field, '') for field in fieldnames}
            writer.writerow(filtered_team)
    
    print(f"✅ 数据已成功保存到 CSV 文件: {filename}")

def display_rankings(east_teams, west_teams):
    """在控制台展示球队排名信息"""
    print("\n🏆 2023-2024 NBA常规赛排名")
    
    print("\n=== 东部联盟 ===")
    for team in east_teams:
        print(f"{team['rank']:2d}. {team['name']:10} | 胜-{team['win']} 负-{team['lose']} | 胜率: {team['rate']} | 近期战绩: {team['recentGame']}")
    
    print("\n=== 西部联盟 ===")
    for team in west_teams:
        print(f"{team['rank']:2d}. {team['name']:10} | 胜-{team['win']} 负-{team['lose']} | 胜率: {team['rate']} | 近期战绩: {team['recentGame']}")

if __name__ == '__main__':
    print("🔍 正在获取2023-2024赛季NBA常规赛排名数据...")
    east_teams, west_teams = fetch_nba_rankings()
    
    if east_teams and west_teams:
        print("✅ 成功获取东部和西部球队数据")
        
        # 在控制台显示排名
        display_rankings(east_teams, west_teams)
        
        # 保存为JSON文件
        save_as_json(east_teams, west_teams)
        
        # 保存为CSV文件
        save_as_csv(east_teams, west_teams)
    else:
        print("❌ 无法获取NBA排名数据，请检查网络连接或稍后再试。")